package com.ruoyi.business.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.business.common.Result;
import com.ruoyi.business.entity.*;
import com.ruoyi.business.entity.dto.Coordinate;
import com.ruoyi.business.entity.dto.HomestayInfoDTO;
import com.ruoyi.business.entity.redis.UserObj;
import com.ruoyi.business.mapper.FrontHomestayInfoMapper;
import com.ruoyi.business.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Ao
 * @since 2024-01-08
 */
@RestController
@RequestMapping("/business/homestayInfo")
@Api(value = "名宿相关接口", tags = "民宿相关接口")
public class FrontHomestayInfoController {
    @Autowired
    private FrontHomestayInfoService homestayInfoService;

    @Autowired
    private FrontCommentsService commentsService;


    @Autowired
    private FrontOrdersService ordersService;


    @Autowired
    private FrontRoomInfoService roomInfoService;


    @Autowired
    private FrontFeaturesService featuresService;


    @Autowired
    private FrontUserService userService;

    @PostMapping("/homepageRecommendation")
    @ApiOperation("主页推荐名宿列表")
    public Result<List<HomestayInfoDTO>> homepageRecommendation(@RequestBody Coordinate coordinate) {
//        //拿到评分最高的四条记录
//        LambdaQueryWrapper<HomestayInfo> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(HomestayInfo::getIdentifyStatus, "1");
//        queryWrapper.orderByDesc(HomestayInfo::getScore); // 按 score 字段降序排序
////        queryWrapper.last("limit 4"); // 获取前4条记录
//
//        List<HomestayInfo> homestayInfoList = homestayInfoService.list(queryWrapper);


        List<HomestayInfo> homestayInfoList = homestayInfoService.selectByDistance(coordinate.getLongitude(), coordinate.getLatitude(), coordinate.getDistance());
        /**
         * 对民宿拿到其对应的评论数
         */
        List<Comments> list = commentsService.list();//所有评论
        List<RoomInfo> list1 = roomInfoService.list();
        List<Features> list2 = featuresService.list();

        List<HomestayInfoDTO> result = new ArrayList<>();

        //遍历民宿
        for (HomestayInfo homestayInfo : homestayInfoList) {
            HomestayInfoDTO homestayInfoDTO = BeanUtil.copyProperties(homestayInfo, HomestayInfoDTO.class);

            Long homestayId = homestayInfo.getHomestayId();

            //获得评论数
            List<Comments> collect = list.stream()
                    .filter(comment -> comment.getHomestayId() == homestayId && comment.getParentDiscussId() == 0)//找到该名宿的父级评论
                    .collect(Collectors.toList());
            int size = collect.size();
            homestayInfoDTO.setNum(size);//获得评论数



            //获得最低价格
            List<RoomInfo> roomInfoList = list1.stream()
                    .filter(item -> item.getHomestayId() == homestayId)
                    .collect(Collectors.toList());

            Float minPrice= Float.valueOf(roomInfoList.get(0).getRoomPrice());
            for (RoomInfo roomInfo : roomInfoList) {
                if(roomInfo.getRoomPrice()<minPrice){
                    minPrice= Float.valueOf(roomInfo.getRoomPrice());
                }
            }
            homestayInfoDTO.setMinPrice(minPrice);



            //获得特色
            List<Features> featuresList = list2.stream()
                    .filter(item -> item.getHomestayId() == homestayId)
                    .collect(Collectors.toList());
            result.add(homestayInfoDTO);

            List<String> list3=new ArrayList<>();
            for (Features features : featuresList) {
                list3.add(features.getFeatureName());
            }
            homestayInfoDTO.setFeaturesList(list3);

        }


        return Result.success(result);
    }


    @GetMapping("/refreshScore")
    @ApiOperation("刷新民宿评分")
    public Result<String> refreshScore() {

        LambdaQueryWrapper<HomestayInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HomestayInfo::getIdentifyStatus, "1");


        List<HomestayInfo> homestayInfoList = homestayInfoService.list(queryWrapper);


        /**
         * 对民宿拿到其对应的评论数
         */
//        List<Comments> list = commentsService.list();//所有评论
        List<Orders> list1 = ordersService.list();

//        List<HomestayInfoDTO> result=new ArrayList<>();

        //遍历民宿
        for (HomestayInfo homestayInfo : homestayInfoList) {
//            HomestayInfoDTO homestayInfoDTO = BeanUtil.copyProperties(homestayInfo, HomestayInfoDTO.class);

            Long homestayId = homestayInfo.getHomestayId();

//            //获得评论数
//            List<Comments> collect = list.stream()
//                    .filter(comment -> comment.getHomestayId() == homestayId && comment.getParentDiscussId() == 0)//找到该名宿的父级评论
//                    .collect(Collectors.toList());
//            int size = collect.size();
//            homestayInfoDTO.setNum(size);
//            //评论数等于父级评论数量

//            获得评分（刷新评分）
            List<Orders> filteredList = list1.stream()
                    .filter(order -> order.getHomestayid() == homestayId && order.getOrderStatus() == 2)//已完成的订单才能评分
                    .collect(Collectors.toList());
            double averageScore = filteredList.stream()
                    .mapToDouble(Orders::getScore)
                    .average()
                    .orElse(0.0);//没有则返回0.0分

            //保留一位小数
            // 创建DecimalFormat对象，指定保留一位小数
            DecimalFormat decimalFormat = new DecimalFormat("#.0");
            // 格式化averageScore为保留一位小数的字符串
            String formattedScore = decimalFormat.format(averageScore);
            // 将格式化后的字符串转换为浮点数
            float formattedFloatScore = Float.parseFloat(formattedScore);
            // 设置给homestayInfo的score属性
            homestayInfo.setScore(formattedFloatScore);

            //更新数据库
            boolean update = homestayInfoService.updateById(homestayInfo);
            if (!update) {
                return Result.error("民宿评分刷新失败");
            }
//            //todo:转为浮点数
//            homestayInfoDTO.setScore((float) averageScore);
//            result.add(homestayInfoDTO);
        }


        return Result.success("民宿更新评分成功");
    }

    //查询指定范围和中心点范围内的民宿

    @Autowired
    private FrontHomestayInfoMapper homestayInfoMapper;
    @ApiOperation(value = "中心点附近的民宿")
    @PostMapping("/homestaylist2")
    public Result<List<HomestayInfo>> homestayInfolist2(@RequestBody Coordinate coordinate){
        if(coordinate==null){
            return Result.error("数据接收错误");
        }

        List<HomestayInfo> homestayInfos = homestayInfoMapper.list2();
        System.out.println(homestayInfos);

        List<HomestayInfo> nearbyHomestays = homestayInfoService.selectByDistance(coordinate.getLongitude(), coordinate.getLatitude(), coordinate.getDistance());
        return Result.success(nearbyHomestays);
    }


    @GetMapping("/getHomestayInfo/{id}")
    @ApiOperation(value = "名宿信息详情接口")
    public Result<HomestayInfoDTO> getHomestayInfo(@PathVariable("id") Long id){

        HomestayInfoDTO homestayInfoDTO = new HomestayInfoDTO();
        //拿到名宿信息
        HomestayInfo homestayInfo = homestayInfoService.getById(id);
        BeanUtil.copyProperties(homestayInfo,homestayInfoDTO);

        //拿到房间信息
        LambdaQueryWrapper<RoomInfo> l1=new LambdaQueryWrapper<>();
        l1.eq(RoomInfo::getHomestayId,id);
        List<RoomInfo> roomInfoList = roomInfoService.list(l1);
        homestayInfoDTO.setRoomInfoList(roomInfoList);

        //拿到特色信息
        LambdaQueryWrapper<Features> l2=new LambdaQueryWrapper<>();
        l2.eq(Features::getHomestayId,id);
        List<Features> featuresList = featuresService.list(l2);
        for(Features feature:featuresList){
            String[] split = feature.getPictures().split(",");
            feature.setPictureList(Arrays.asList(split));
        }
        homestayInfoDTO.setFeaturesInfoList(featuresList);




        //拿到评论条数
        List<Comments> list = commentsService.list();
        List<Comments> collect = list.stream()
                .filter(comment -> comment.getHomestayId() == id && comment.getParentDiscussId() == 0)//找到该名宿的父级评论
                .collect(Collectors.toList());
        int size = collect.size();
        homestayInfoDTO.setNum(size);//获得评论数

        Comments comments = collect.get(0);
        homestayInfoDTO.setComments(comments);//拿到第一条评论信息
        String userid = comments.getUserid();
        LambdaQueryWrapper<User> l3=new LambdaQueryWrapper<>();
        l3.eq(User::getUserid,userid);
        User commentsUser = userService.getOne(l3);
        homestayInfoDTO.setCommentsUser(commentsUser);//拿到第一条评论的用户信息

        return Result.success(homestayInfoDTO);
    }


    @GetMapping("/list")
    public Result<List<HomestayInfoDTO>> list(){
        List<HomestayInfo> homestayInfoList = homestayInfoService.list();
        /**
         * 对民宿拿到其对应的评论数
         */
        List<Comments> list = commentsService.list();//所有评论
        List<RoomInfo> list1 = roomInfoService.list();
        List<Features> list2 = featuresService.list();

        List<HomestayInfoDTO> result = new ArrayList<>();

        //遍历民宿
        for (HomestayInfo homestayInfo : homestayInfoList) {
            HomestayInfoDTO homestayInfoDTO = BeanUtil.copyProperties(homestayInfo, HomestayInfoDTO.class);

            Long homestayId = homestayInfo.getHomestayId();

            //获得评论数
            List<Comments> collect = list.stream()
                    .filter(comment -> comment.getHomestayId() == homestayId && comment.getParentDiscussId() == 0)//找到该名宿的父级评论
                    .collect(Collectors.toList());
            int size = collect.size();
            homestayInfoDTO.setNum(size);//获得评论数



            //获得最低价格
            List<RoomInfo> roomInfoList = list1.stream()
                    .filter(item -> item.getHomestayId() == homestayId)
                    .collect(Collectors.toList());

            Float minPrice= Float.valueOf(0);
            if(roomInfoList.size()!=0){
                 minPrice= Float.valueOf(roomInfoList.get(0).getRoomPrice());
                for (RoomInfo roomInfo : roomInfoList) {
                    if(roomInfo.getRoomPrice()<minPrice){
                        minPrice= Float.valueOf(roomInfo.getRoomPrice());
                    }
                }
                homestayInfoDTO.setMinPrice(minPrice);
            }




            //获得特色
            List<Features> featuresList = list2.stream()
                    .filter(item -> item.getHomestayId() == homestayId)
                    .collect(Collectors.toList());
            result.add(homestayInfoDTO);

            List<String> list3=new ArrayList<>();
            for (Features features : featuresList) {
                list3.add(features.getFeatureName());
            }
            homestayInfoDTO.setFeaturesList(list3);

        }


        return Result.success(result);
    }



        @GetMapping("/search")
        public Result<List<HomestayInfoDTO>> search(Float comment_score,Float min_price,Float max_price,String homestayname,Long homestay_type){
            List<HomestayInfo> homestayInfoList = homestayInfoMapper.searchHomestayByConditions(comment_score, min_price, max_price, homestayname, homestay_type);


            /**
             * 对民宿拿到其对应的评论数
             */
            List<Comments> list = commentsService.list();//所有评论
            List<RoomInfo> list1 = roomInfoService.list();
            List<Features> list2 = featuresService.list();

            List<HomestayInfoDTO> result = new ArrayList<>();

            //遍历民宿
            for (HomestayInfo homestayInfo : homestayInfoList) {
                HomestayInfoDTO homestayInfoDTO = BeanUtil.copyProperties(homestayInfo, HomestayInfoDTO.class);

                Long homestayId = homestayInfo.getHomestayId();

                //获得评论数
                List<Comments> collect = list.stream()
                        .filter(comment -> comment.getHomestayId() == homestayId && comment.getParentDiscussId() == 0)//找到该名宿的父级评论
                        .collect(Collectors.toList());
                int size = collect.size();
                homestayInfoDTO.setNum(size);//获得评论数



                //获得最低价格
                List<RoomInfo> roomInfoList = list1.stream()
                        .filter(item -> item.getHomestayId() == homestayId)
                        .collect(Collectors.toList());

                Float minPrice2= Float.valueOf(roomInfoList.get(0).getRoomPrice());
                for (RoomInfo roomInfo : roomInfoList) {
                    if(roomInfo.getRoomPrice()<minPrice2){
                        minPrice2= Float.valueOf(roomInfo.getRoomPrice());
                    }
                }
                homestayInfoDTO.setMinPrice(minPrice2);



                //获得特色
                List<Features> featuresList = list2.stream()
                        .filter(item -> item.getHomestayId() == homestayId)
                        .collect(Collectors.toList());
                result.add(homestayInfoDTO);

                List<String> list3=new ArrayList<>();
                for (Features features : featuresList) {
                    list3.add(features.getFeatureName());
                }
                homestayInfoDTO.setFeaturesList(list3);

            }

            return Result.success(result);
        }

}

